<template>
    <div>
        <van-nav-bar title="搜索" left-text="返回" left-arrow @click-left="onClickLeft" />
        <van-search v-model="seaName" show-action placeholder="鸡蛋">
            <template #action>
                <div @click="handleSea" style="color:red">搜索</div>
            </template>
        </van-search>
        <div class="box">
            <h1>
                历史搜索
                <van-icon name="delete-o" @click="handleClearAllHistory" style="float:right;"/>
            </h1>
            <div v-for="item in searchList" :key="item" style="float: left;">
                <button @click="setSearch(item)">{{ item }}</button>
            </div><br/><br/><br/>
            <h1>热门搜索</h1>
            <div>
                <button @click="setSearch('梨')">梨</button>
                <button @click="setSearch('苹果')">苹果</button>
                <button @click="setSearch('西瓜')">西瓜</button>
                <button @click="setSearch('葡萄')">葡萄</button>
                <button @click="setSearch('青椒')">青椒</button>
                <button @click="setSearch('油麦菜')">油麦菜</button>
                <button @click="setSearch('荷兰豆')">荷兰豆</button>
                <button @click="setSearch('西红柿')">西红柿</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
const onClickLeft = () => history.back();
const router = useRouter()
const seaName = ref('')
const searchList=ref([])
// 设置输入框为按钮的文本
const setSearch=(item)=>{
    seaName.value = item
    router.push(`/type?name=${seaName.value}`)
}
// 监听输入框的值变化
const handleInput = () => {
  // 如果输入框为空，则不执行任何操作
  if (!seaName.value) {
    return
  }
  // 将输入框的值添加到历史搜索记录中
  searchList.value.unshift(seaName.value)
  // 保存历史搜索记录到 localStorage
  saveSearchList()
  // 清空输入框的值
  seaName.value = ''
}
// 获取存储的历史搜索记录
const loadSearchList = () => {
  const storedSearchList = localStorage.getItem('searchList')
  if (storedSearchList) {
    searchList.value = JSON.parse(storedSearchList)
  }
}
// 保存历史搜索记录到 localStorage
const saveSearchList = () => {
  localStorage.setItem('searchList', JSON.stringify(searchList.value))
}
// 处理搜索
const handleSea = () => {
  if (seaName.value) {
    searchList.value.unshift(seaName.value)  // 将搜索内容添加到历史记录开头
    searchList.value = [...new Set(searchList.value)] // 确保没有重复的记录
    saveSearchList()
  }
  // 跳转到结果页面
  router.push(`/type?name=${seaName.value}`)
}
// 清空历史记录
const handleClearAllHistory = () => {
  if (window.confirm("确定要清空所有历史记录吗？")) {
    searchList.value = []  // 清空历史记录
    saveSearchList()  // 保存空数组到 localStorage
  }
}

// 页面加载时，初始化搜索历史
onMounted(() => {
  loadSearchList()
})
</script>

<style scoped lang="scss">
.box{
    width: 90%;
    height: 300px;
    margin: 0 auto;
    button{
        background: rgb(242, 242, 242);
        margin-right: 15px;
        border: none;
        margin-top: 20px;
        border-radius: 30px;
    }
}
</style>